package com.wontube.smr.bo.media;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.client.extension.utils.StringUtils;



public final class NativeMediaConverter {
	private static final Logger logger = LoggerFactory.getLogger(NativeMediaConverter.class);

	public static boolean toMp3(String inputPath, String outFilename, boolean deleteSrc) {
		File inputFile = new File(inputPath);
		if (!inputFile.exists()) {
			return false;
		}
		
		File outputFile = new File(outFilename);
		String command = System.getProperty("os.name").toUpperCase().startsWith("WINDOWS") 
				? StringUtils.format("ffmpeg.exe -y -i \"{}\" -ar 44100 -ab 192000 \"{}\"", inputPath, outputFile.getPath())
				: StringUtils.format("ffmpeg -y -i {} -ar 44100 -ab 192000 {}", inputPath, outputFile.getPath());

		Runtime runtime = Runtime.getRuntime();
		Process process = null;
		try {
			process = runtime.exec(command);
			StreamGobbler err = new StreamGobbler(process.getErrorStream()); 
			StreamGobbler out= new StreamGobbler(process.getInputStream());
            err.start();  
            out.start();  
            
			int exitCode = process.waitFor();
			if (exitCode == 0) {
				return true;
			}
		} catch (Exception e) {
			logger.error(e.toString());
		} finally {
			if (process != null && process.getOutputStream() != null) {
				try {
					process.getOutputStream().close();
				} catch (IOException e) {
					logger.error(e.toString());
				}
			}
			if (deleteSrc) {
				int tryTimes = 1;
				while (!inputFile.delete() && tryTimes < 5) {
					logger.debug("delete file " + inputFile.getName() + " failed, try again...");
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
					}
					tryTimes++;
				}
			}
		}

		return false;
	}

	private static class StreamGobbler extends Thread {
		private InputStream is;

		public StreamGobbler(InputStream is) {
			this.is = is;
		}
		
		public void run() {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			try {
				while (br.readLine() != null);
			} catch (IOException e) {
				NativeMediaConverter.logger.error(e.toString());
			} finally {
				try {
					isr.close();
					br.close();
					this.is.close();
				} catch (IOException e) {
					NativeMediaConverter.logger.error(e.toString());
				}
			}
		}
	}
}


